package com.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ThreadDemo {

    List<Integer> peaches;

    public ThreadDemo(){
        this.peaches = new ArrayList<>(Collections.nCopies(500, 1));//桃树原有的500个桃子
    }

    /*
    * Monkey线程每隔0.1秒消费桃子
    * */
    class Monkey extends Thread{
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(100);
                    peaches.remove(0);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    /*
     * 桃树线程每隔0.3秒生产桃子诺干
     * */
    class PeachTree extends Thread{
        @Override
        public void run() {
            Random random = new Random();
            while(true){
                try {
                    Thread.sleep(300);
                    int num = random.nextInt(10) + 1;
                    for(int i = 0; i < num; i++) {
                        peaches.add(i);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /*
     * 仙女线程每隔0.5秒数桃子
     * */
    class Xiannv extends Thread{
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(500);
                    System.out.println(peaches.size());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //行为模拟
    public void process(){
        Monkey monkey = new Monkey();
        monkey.start();
        PeachTree peachTree = new PeachTree();
        peachTree.start();
        Xiannv xiannv = new Xiannv();
        xiannv.start();
    }
    public static void main(String[] args){
        ThreadDemo td = new ThreadDemo();
        td.process();
    }
}

